package org.aeon.client.context;

import io.netty.channel.Channel;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.aeon.Main;
import org.aeon.client.view.ApplicationUI;
import org.aeon.client.view.components.listColumn.ListColumnPanel;
import org.aeon.client.view.components.sessionPanel.SessionPanel;
import org.aeon.entity.ChatMessage;
import org.aeon.entity.User;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author: MissingAeon
 * @date: 2024/1/26 9:13
 * @description: 上下文
 */
@Slf4j
@Getter
@Setter
public class GlobalContext {
    @Getter
    private static final GlobalContext context = new GlobalContext();
    private final Map<String, CountDownLatch> waits = new HashMap<>();
    // 线程池
    private final ExecutorService threadPool = Executors.newCachedThreadPool();
    // 提示弹窗线程池
    private final ThreadPoolExecutor singleThreadExecutor = new ThreadPoolExecutor(1, 1,
            0L, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new ThreadPoolExecutor.DiscardPolicy());

    private final AtomicBoolean isLogin = new AtomicBoolean(false);
    private final ConcurrentHashMap<String, ChatMessage> userChatMap = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, ChatMessage> groupChatMap = new ConcurrentHashMap<>();
    private final MessageMap messageMap = new MessageMap();
    private String token;
    private User currentUser;
    private Channel channel;

    private ApplicationUI mainUI;
    private ListColumnPanel listColumnPanel;
    private SessionPanel sessionPanel;

    public Channel getChannel() {
        if (channel != null) {
            return channel;
        }
        if (mainUI != null) {
            mainUI.dispose();
            mainUI = null;
            Main.startUp();
            return getChannel();
        }
        return null;
    }

    public void shutdownGracefully() {
        log.debug("正在关闭...");
        GlobalContext.getContext().getThreadPool().shutdown();
        GlobalContext.getContext().getSingleThreadExecutor().shutdownNow();
        if (channel != null) {
            channel.close();
        }
    }
}
